package com.lx.core.spring;


import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.concurrent.ThreadFactory;

/**
 * 配置spring 设置启动监听设置
 * spring 加载完成后会执行一些事情 在<code>@PostConstruct</code>
 */
@Slf4j
public abstract class SpringRefreShedListener implements ApplicationListener<ContextRefreshedEvent> {
    private ThreadFactory newNamedThreadFactory = ThreadUtil.newNamedThreadFactory("AsyncRunAfterStart_Thread", true);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        final ApplicationContext ctx = event.getApplicationContext();
        runInit(ctx);
    }

    abstract protected void runInit(ApplicationContext ctx);

    protected void runInit(final RunAfterStart r, final Object... args) {
        if (r instanceof AsyncRunAfterStart) {
            try {
                newNamedThreadFactory.newThread(() -> {
                    r.runInit(args);
                }).start();
            } catch (Exception e) {
                log.error("{}", e);
            }
        } else {
            try {
                r.runInit(args);
            } catch (Exception e) {
                log.error("加载异常:{}", e);
                throw new RuntimeException();
            }
        }
    }

    protected void runInit(ApplicationContext ctx, Class<? extends RunAfterStart> clazz, final Object... args) {
        final RunAfterStart bean = ctx.getBean(clazz);
        runInit(bean, args);
    }
}
